<?php
/**
 * 微信用户模型
 * @Author: phpzhi <phpzhi@qq.com><https://www.phpzhi.com>
 * @Date: 2019/11/7 11:00
 */

namespace app\common\model\wechat;


use app\common\model\User;
use think\Model;

class WechatUser extends Model
{
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    protected $name = 'wechat_user';

    public static function saveWechatUserInfo($data)
    {
        $wechatUser['nickname'] = $data['nickName'];
        $wechatUser['gender'] = $data['gender'];
        $wechatUser['language'] = $data['language'];
        $wechatUser['city'] = $data['city'];
        $wechatUser['province'] = $data['province'];
        $wechatUser['country'] = $data['country'];
        $wechatUser['avatar'] = $data['avatarUrl'];
        $wechatUser['routine_openid'] = $data['openId'];
        $wechatUser['session_key'] = $data['session_key'];
        $wechatUser['unionid'] = $data['unionId'] ?: '';
        $wechatUser['user_type'] = 'routine';
        $spread_id = 0;
        $isCode = false;

        // 是否有扫码进入小程序
        if ($data['spread_code']) {
            if ($qrCode = WechatQrcode::getWechatQrcodeById($data['spread_code'])) {
                $spread_id = $qrCode['third_id'];
                $isCode = true;
            } else {
                $spread_id = $data['spread_id'];
            }
        } else if ($data['spread_id']) {
            $spread_id = $data['spread_id'];
        }

        if ($wechatUser['unionid'] != '' && $id = self::where(['unionid' => $wechatUser['unionid']])->where('user_type', '<>', 'h5')->value('id')) { // unionid 是否存在
            self::update($wechatUser, ['id' => $id]);
            $wechatUser['spread_code'] = $spread_id;
            $wechatUser['is_spreader'] = $isCode;
            if ($data['login_type']) $wechatUser['login_type'] = $data['login_type'];
            User::updateWechatUser($wechatUser, $id);
        } else if ($id = self::where(['routine_openid' => $wechatUser['routine_openid']])->where('user_type', '<>', 'h5')->value('id')) { // openid是否存在
            self::update($wechatUser, ['id' => $id]);
            $wechatUser['spread_code'] = $spread_id;
            $wechatUser['is_spreader'] = $isCode;
            if ($data['login_type']) $wechatUser['login_type'] = $data['login_type'];
            User::updateWechatUser($wechatUser, $id);
        } else { // 都不存在,两个表都创建
            $wechatUser = self::create($wechatUser);
            $id = User::addWechatUser($wechatUser, $spread_id); // TODO
        }
        return $id;
    }
}
